package com.resou.reader.search.search2;

import android.content.ContentValues;
import android.util.Log;
import android.widget.Toast;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.CommonData;
import com.resou.reader.api.entry.SearchBean;
import com.resou.reader.api.service.SearchService;
import com.resou.reader.bookshelf.readhistory.datasupport.DataSupport;
import com.resou.reader.bookshelf.readhistory.datasupport.SearchHistory;
import com.resou.reader.mine.IView.UserInstance;

import org.litepal.LitePal;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class Search2Presenter {
    private Search2Activity mActivity;
    private boolean isRequestInProgress = false;
    private SearchService mService;
    private final CompositeDisposable mCompositeDisposable;
    private int mCurrentPage = 0;
    private static final String TAG = "Search2Presenter";

    public Search2Presenter(Search2Activity activity) {
        mActivity = activity;
        mCompositeDisposable = new CompositeDisposable();
        mService = ApiImp.getInstance().getService(SearchService.class);
    }

    public void getHotWord() {
        mCompositeDisposable.add(
                mService.searchPush()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(commonDataResult -> {
                            if (commonDataResult.getData() != null) {
                                mActivity.showHotWord(commonDataResult.getData().getData());
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                mActivity.showError(throwable);
                            }
                        })
        );
    }

    public void search(String query) {
        if (isRequestInProgress) {
            return;
        }
        saveQuery(query);
        isRequestInProgress = true;
        mCompositeDisposable.add(

                mService.search(query, UserInstance.getToken(), 0, 10)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(commonDataResult -> {
                                    CommonData<List<SearchBean>> commonData = commonDataResult.getData();
                                    mActivity.showSearchResult(commonData.getData(), query);
                                    mCurrentPage = 1;
                                }, Throwable -> {
                                    isRequestInProgress = false;
                                    mActivity.showSearchResult(null, query);
                                    mActivity.showError(Throwable);
                                }, () -> {
                                    isRequestInProgress = false;
                                }
                        )
        );
    }

    /**
     * 通过关键字搜索
     *
     * @param query
     */
    public void searchKeyWord(String query) {
        mCompositeDisposable.add(
                mService.search(query, UserInstance.getToken(), 0, 10)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(commonDataResult -> {
                                    CommonData<List<SearchBean>> commonData = commonDataResult.getData();
                                    mActivity.showKeyWordResult(commonData.getData(), query);
                                }, Throwable -> {
                                    mActivity.showKeyWordResult(null, query);
                                    mActivity.showError(Throwable);
                                }
                        )
        );
    }

    public void searchNext(String query) {
        if (isRequestInProgress) {
            return;
        }
        isRequestInProgress = true;
        mCompositeDisposable.add(
                mService.search(query, UserInstance.getToken(), mCurrentPage, 10)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(commonDataResult -> {
                                    CommonData<List<SearchBean>> commonData = commonDataResult.getData();
                                    mActivity.addSearchResult(commonData.getData(), query);
                                    mCurrentPage = mCurrentPage + 1;
                                }, Throwable -> {
                                }, () -> {
                                    isRequestInProgress = false;
                                }
                        )
        );
    }

    /**
     * 存搜索数据
     */
    private synchronized void saveQuery(final String query) {
        mCompositeDisposable.add(
                Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                    SearchHistory historyQuery = LitePal.where("history = ?", query).findFirst(SearchHistory.class);
                    if (historyQuery == null) {
                        emitter.onNext(-1);
                    } else {
                        emitter.onNext(historyQuery.getId());
                    }
                })
                        .observeOn(Schedulers.io())
                        .subscribe(id -> {
                            if (id != -1) {
                                ContentValues values = new ContentValues();
                                values.put("updateTime", System.currentTimeMillis());
                                LitePal.update(SearchHistory.class, values, id);
                            } else {
                                Log.i(TAG, "saveQuery: 保存数据");
                                SearchHistory temp = new SearchHistory(query, System.currentTimeMillis());
                                temp.save();
                            }
                        })
        );
    }

    /**
     * 获取搜索数据
     */
    public void getAllHistory() {
        mCompositeDisposable.add(
                Observable.create((ObservableOnSubscribe<List<SearchHistory>>) emitter -> {
                    List<SearchHistory> list = LitePal.select("history").order("updateTime desc").find(SearchHistory.class);
                    emitter.onNext(list);
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(searchHistories -> {
                                    mActivity.showHistorySearch(searchHistories);
                                }, throwable -> {

                                }
                        ));
    }

    /**
     * 删除所有搜索历史
     */
    public void deleteAllHistory() {
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            LitePal.deleteAll(SearchHistory.class);
            emitter.onNext(true);
        })
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe();
    }
}
